import 'dart:ui';
import 'package:eh_mobile/common/store/index.dart';
import 'package:eh_mobile/common/utils/index.dart';
import 'package:eh_mobile/common/utils/web_rtc_channel.dart';
import 'package:eh_mobile/common/values/svg_image.dart';
import 'package:eh_mobile/pages/main/smart_home_info/widgets/custom_switch.dart';
import 'package:eh_mobile/pages/main/smart_home_info/widgets/light_card_item.dart';
import 'package:eh_mobile/pages/main/smart_home_info/widgets/room_list_tabbar.dart';
import 'package:eh_mobile/pages/main/smart_home_info/widgets/staggered_draggable_sort.dart';
import 'package:eh_mobile/pages/main/smart_home_info/widgets/temp_card_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import '../../../common/utils/web_rtc_channel_common.dart';
import '../../../global.dart';
import '../homepage/common/home_page_common_utils.dart';
import '../homepage/model/home_device_model.dart';
import 'index.dart';
import 'model/device_dynamic_model.dart';
import 'model/device_report_cmd_model.dart';

class SmartHomeInfoPage extends StatefulWidget {
  List<HomeDeviceModelDevices>? devices;
  HomeDeviceModelData? itemData;
  DeviceDynamicModelData? dynamicModelData;
  Function? callBackModel;

  SmartHomeInfoPage(
      {this.devices,
      super.key,
      this.itemData,
      this.dynamicModelData,
      this.callBackModel});

  @override
  State<SmartHomeInfoPage> createState() => _SmartHomeInfoPageState();
}

class _SmartHomeInfoPageState extends State<SmartHomeInfoPage> {
  Color cornerBgColor = const Color.fromRGBO(255, 255, 255, 0.08);
  Color cornerBorderColor = const Color.fromRGBO(222, 222, 222, 0.5);
  SmartHomeInfoController controller = Get.put(SmartHomeInfoController());

  // 主视图
  Widget _buildView(BuildContext context) {
    return Stack(
      children: [
        Column(
          children: [
            Obx(
              () => AnimatedContainer(
                duration: const Duration(microseconds: 300),
                width: 1.sw,
                curve: Curves.easeInOut,
                height: ScreenUtil().statusBarHeight +
                    (controller.editOpen.value ? 46.r : 90.r),
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                clipBehavior: Clip.none,
                controller: controller.scrollController,
                child: Container(child: _buildWiringSetCard()),
              ),
            ),
          ],
        ),
        ClipRRect(
          child: BackdropFilter(
              filter: ImageFilter.blur(
                  sigmaX: 10, sigmaY: 10, tileMode: TileMode.mirror),
              child: Obx(
                () => AnimatedContainer(
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                  height: ScreenUtil().statusBarHeight +
                      (controller.editOpen.value ? 46.r : 90.r),
                  color: const Color.fromRGBO(28, 28, 28, 0.75),
                ),
              )),
        ),
        // 阴影分割线
        _buildShadowDashLine(),

        // 创建标题
        _buildTitleWidget(),

        Obx(
          () => Positioned(
            top: ScreenUtil().statusBarHeight + 44.r,
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 300),
              height: controller.editOpen.value ? 0 : 46.r,
              width: 1.sw,
              child: Stack(
                alignment: Alignment.bottomCenter,
                children: [
                  //全部开启 全部关闭按钮
                  _buildPushButtonWidget(),
                  // 房间选择滚动视图
                  _buildRoomTabbar(),
                ],
              ),
            ),
          ),
        ),
        // 右侧点击事件
        _buildRightButton(),
      ],
    );
  }

  // 构建头部房间标题
  Widget _buildTitleWidget() {
    String title = '';
    if (widget.itemData != null) {
      title = widget.itemData!.name ?? '';
    }

    return Positioned(
        left: 12.r,
        top: ScreenUtil().statusBarHeight + 2.r,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              height: 32.r,
              child: Text(
                title,
                style: 22.ts,
              ),
            ),
            5.sizedBoxWidth,
            Obx(
              () => AnimatedOpacity(
                duration: const Duration(milliseconds: 300),
                opacity: controller.editOpen.value ? 0 : 1,
                child: Visibility(
                  visible: controller.subTitleHidden.value,
                  child: SizedBox(
                    height: 16.r,
                    child: Text(
                      controller.subTitle.value,
                      style: 14.ts,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ));
  }

  // 右侧上交点击按钮
  Widget _buildRightButton() {
    return Positioned(
        top: ScreenUtil().statusBarHeight,
        right: 0,
        child: Obx(() => AnimatedContainer(
              duration: const Duration(milliseconds: 300),
              width: controller.editOpen.value ? 52.r : 42.r,
              height: 32.r,
              padding: const EdgeInsets.fromLTRB(0, 4, 0, 4).r,
              margin: const EdgeInsets.only(right: 12, bottom: 12).r,
              decoration: BoxDecoration(
                color: const Color.fromRGBO(222, 222, 222, 0.1),
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: SvgPicture.asset(
                controller.editOpen.value
                    ? SVGImage.icOkSvg
                    : SVGImage.icCloseSSvg,
                fit: BoxFit.fitHeight,
                colorFilter:
                    const ColorFilter.mode(Colors.white, BlendMode.srcIn),
              ),
            ).onClick(() {
              if (controller.editOpen.value) {
                controller.editOpen.value = false;
                controller.update([controller.smartHomeInfoId]);
                UserStore().userStoreCache.write('light', widget.devices);
              } else {
                List temp = [];
                //给数据加标识
                for (var i = 0; i < controller.roomList.length; i++) {
                  List list = controller.lightList[i];
                  for (var j = 0; j < list.length; j++) {
                    temp.add(list[j]);
                  }
                }
                if (widget.callBackModel != null) {
                  widget.callBackModel!(temp);
                }
                Get.back();
              }
            })));
  }

  //分割线阴影
  Widget _buildShadowDashLine() {
    return Obx(() => Positioned(
        top: ScreenUtil().statusBarHeight +
            76.r -
            (controller.editOpen.value ? 44.r : 0),
        child: Container(
          alignment: Alignment.bottomCenter,
          height: 14.r,
          width: 1.sw,
          decoration: BoxDecoration(
              color: Colors.transparent,
              boxShadow: controller.state.scrollViewDidScroll
                  ? [
                      const BoxShadow(
                          color: Color.fromRGBO(0, 0, 0, 0.55),
                          offset: Offset(0, 5),
                          blurRadius: 30)
                    ]
                  : null),
          child: controller.state.scrollViewDidScroll
              ? Container(
                  color: cornerBgColor,
                  height: 1,
                )
              : Container(),
        )));
  }

  // 创建顶部房间选择tabbar
  Widget _buildRoomTabbar() {
    return Obx(
      () => AnimatedPositioned(
          top: 0,
          left: controller.state.scrollViewDidScroll ? 0 : 1.sw,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          child: RoomListTabbar(
            roomList: controller.roomList,
            onTabChanged: (value) {
              controller.onTabChange(value);
            },
          )),
    );
  }

  // 顶部开关部件
  Widget _buildPushButtonWidget() {
    return Obx(
      () => AnimatedPositioned(
        top: 0,
        left: controller.state.scrollViewDidScroll ? -1.sw : 0,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
        child: Container(
          alignment: Alignment.centerLeft,
          padding: const EdgeInsets.only(
            left: 12,
            right: 12,
          ).r,
          child: Row(
            children: [
              Container(
                width: 88.w,
                height: 32.h,
                decoration: BoxDecoration(
                  color: cornerBgColor,
                  border: Border.all(color: cornerBorderColor, width: 1),
                  borderRadius: const BorderRadius.all(Radius.circular(9)),
                ),
                child: TextButton(
                  style: ButtonStyle(
                      padding: MaterialStateProperty.all(EdgeInsets.zero)),
                  onPressed: () {
                    controller.allControlDeviceClick(false);
                  },
                  child: Text(
                    '全部关闭',
                    style: 14.ts,
                  ),
                ),
              ),
              12.sizedBoxWidth,
              Container(
                width: 88.w,
                height: 32.r,
                decoration: BoxDecoration(
                  color: cornerBgColor,
                  border: Border.all(color: cornerBorderColor, width: 1),
                  borderRadius: const BorderRadius.all(Radius.circular(9)),
                ),
                child: TextButton(
                  style: ButtonStyle(
                      padding: MaterialStateProperty.all(EdgeInsets.zero)),
                  onPressed: () {
                    controller.allControlDeviceClick(true);
                  },
                  child: Text(
                    '全部打开',
                    style: 14.ts,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 创建所有房间设备集合卡片
  Widget _buildWiringSetCard() {
    var widgets = <Widget>[];
    for (var i = 0; i < controller.roomList.length; i++) {
      widgets.add(_buildHeadTitleView(controller.roomList[i], i));
      widgets.add(
        GetBuilder<SmartHomeInfoController>(
          id: controller.roomList[i],
          builder: (SmartHomeInfoController homeInfoController) {
            return _buildLightCardView(i, homeInfoController.roomList[i]);
          },
        ),
      );
    }

    widgets.add(
      SizedBox(
        width: 1.sw,
        height: ScreenUtil().bottomBarHeight,
      ),
    );
    return Column(children: widgets);
  }

  // 房间标题
  Widget _buildHeadTitleView(String title, int index) {
    return Container(
      padding: const EdgeInsets.only(left: 12, right: 12, top: 10),
      key: controller.roomTitleGlobalKeys[index],
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(title, style: 16.ts),
          CustomSwitch(
            onChanged: (value) {
              controller.sectionControlDeviceClick(index, value);
            },
            value: controller.judgeSectionAllDeviceIsClose(index),
          ),
        ],
      ),
    );
  }

  // 创建每一个房间设备卡片集合
  Widget _buildLightCardView(int index, String builderId) {
    var items = <StaggeredItem>[];
    var lightModelList = controller.lightList[index];
    for (var i = 0; i < lightModelList.length; i++) {
      HomeDeviceModelDevices lightCardModel = lightModelList[i];
      // 根据页面传入类型创建不同的设备卡片
      Widget deviceCardItem;
      if (controller.deviceLListType == DeviceLListType.light) {
        deviceCardItem = _buildLightCardItem(lightCardModel, i);
      } else {
        deviceCardItem = _buildTempCardItem(lightCardModel, i);
      }
      StaggeredItem cuntomItem = StaggeredItem(
          key: "key_$index$i",
          child: deviceCardItem,
          canOpen: lightCardModel.online!,
          crossAxisCellCount: 2,
          mainAxisCellCount: lightCardModel.cardOpen! ? 2 : 1,
          unfoldCloseColor: lightCardModel.hasEvent!
              ? const Color(0xff323232)
              : const Color(0xffEBEBEB));
      items.add(cuntomItem);
    }

    return Container(
      width: 1.sw,
      padding: const EdgeInsets.fromLTRB(0, 10, 0, 0).r,
      child: StaggeredDraggableSortView(
        columnNum: 2,
        padding: const EdgeInsets.fromLTRB(14, 0, 14, 0).r,
        aspectRatio: 0.77,
        canDrag: controller.editOpen.value,
        staggeredModelList: items,
        itemExchanged: (moveIndex, toIndex) {
          final item = controller.lightList.removeAt(moveIndex);
          controller.lightList.insert(toIndex, item);
        },
        cardOpenChanged: (index, open) {
          HomeDeviceModelDevices lightCardModel = lightModelList[index];
          lightCardModel.cardOpen = open;
        },
      ),
    );
  }

  // 创建灯光设备卡片
  Widget _buildLightCardItem(HomeDeviceModelDevices lightCardModel, int index) {
    return GetBuilder(
        id: lightCardModel.devId,
        builder: (SmartHomeInfoController homeInfoController) {
          return LightCardItem(
            lightCardModel,
            editOpen: controller.editOpen.value,
            lightCardEditCallback: (value) {
              controller.editOpen.value = true;
              controller.update([controller.smartHomeInfoId]);
            },
            renameCallback: (name) {
              lightCardModel.name = name;
            },
            cardTapCallback: () {
              controller.lightCardItemAction(index, lightCardModel.name!);
            },
            cardEventCallback: (value) {
              String isOn = 'off';
              if (value == true) {
                isOn = 'on';
              } else {
                isOn = 'off';
              }
              WebRtcChannelCommon.sendChannelDeviceWrite(
                  WebRtcChannel().sendChannel,
                  item: lightCardModel,
                  dataMap: {'power': isOn});
              lightCardModel.last?.power = isOn;
              lightCardModel.hasEvent = value;
              controller
                  .update([lightCardModel.devId ?? controller.smartHomeInfoId]);
            },
          );
        });
  }

  // 创建恒温设备卡片
  Widget _buildTempCardItem(HomeDeviceModelDevices lightCardModel, int index) {
    return TempCardItem(
      lightCardModel,
      editOpen: controller.editOpen.value,
      lightCardEditCallback: (value) {
        controller.editOpen.value = true;
        controller.update([controller.smartHomeInfoId]);
      },
      renameCallback: (name) {
        lightCardModel.name = name;
      },
      cardTapCallback: () {
        controller.lightCardItemAction(index, lightCardModel.name!);
      },
      cardEventCallback: (value) {
        lightCardModel.hasEvent = value;
        controller.update([controller.smartHomeInfoId]);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SmartHomeInfoController>(
      init: SmartHomeInfoController(),
      id: controller.smartHomeInfoId,
      builder: (_) {
        return Scaffold(
          body: _buildView(context),
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
    Set<String?> reginList = {};
    //分区
    widget.devices?.forEach((element) {
      if (element.region_name != null) {
        reginList.add(element.region_name);
      }
    });
    controller.roomList.addAll(reginList);
    controller.handleDataFromSection(widget.devices);
    Global.webRtcChannel.receiveReportBlock = (DeviceReportCmdModel res) {
      HomeDeviceModelDevices? reportModel;
      for (var i = 0; i < controller.roomList.length; i++) {
        List sectionList = controller.lightList[i];
        try {
          reportModel = sectionList
              .singleWhere((element) => element.devId == res.data?.id);
        } catch (e) {
          reportModel = null;
        }
      }
      if (reportModel != null) {
        reportModel.hasEvent = res.data?.data?.power == 'on';
        controller.update([reportModel.devId ?? '']);
      }
    };

    Global.webRtcChannel.receiveDynamicBlock = (DeviceDynamicModelCmd res) {
      if (res.data!.devices!.isNotEmpty) {
        controller.subTitle.value = '${res.data?.devices?.length}盏灯亮着';
        controller.subTitleHidden.value = true;
      } else {
        controller.subTitleHidden.value = false;
      }
    };
    if (widget.dynamicModelData!.devices != null &&
        widget.dynamicModelData!.devices!.isNotEmpty) {
      controller.subTitle.value =
          HomePageCommonUtils.getRightDeviceInfo(widget.dynamicModelData!);
      controller.subTitleHidden.value = true;
    } else {
      controller.subTitleHidden.value = false;
    }
  }
}
